import { Dictionary } from "../../Common/Dictionary";
import ADQ from "../../Core/ADQ";
import {
  IStateMachine,
  IStateMachineManager,
} from "../../Interfaces/IStateMachine";
import { IDictionary } from "../../Interfaces/IUtils";

/**
 * 状态机管理器
 */
export class StateMachineManager implements IStateMachineManager {
  static InvalidState: number = 0; //默认状态
  protected _stateDic: IDictionary<number, IStateMachine>;
  protected _currentState: IStateMachine;
  protected _lastState: IStateMachine;
  protected _owner: any;
  /**所有者 */
  public get owner(): any {
    return this._owner;
  }

  constructor(owner: any) {
    this._owner = owner;
    this._stateDic =new Dictionary<number, IStateMachine>();
  }
  setOwner(owner: any) {
    this._owner = owner;
  }
  registerState(stateKey: number, state: IStateMachine) {
    if (this._owner != state.owner) {
      console.debug("state_machine 和 state的所有者不一样");
      return;
    }
    this._stateDic.set(stateKey, state);
  }
  isExist(stateKey: any): Boolean {
    return this._stateDic.containsKey(stateKey);
  }
  changeState(stateKey: number, obj?: any) {
    var newState: IStateMachine = this._stateDic.get(stateKey);
    if (newState == null) {
      console.debug("unregister state : " + stateKey);
      return;
    }

    if (this._currentState != null) {
      this._currentState.onLeave(newState.getStateKey());
    }
    this._currentState = newState;
    this._currentState.onEnter(obj);
  }
  update() {
    if (this._currentState != null) this._currentState.onUpdate();
  }
  getCurrentState(): number {
    if (this._currentState != null) {
      return this._currentState.getStateKey();
    }
    return StateMachineManager.InvalidState;
  }
  clear() {
    if (this._currentState != null)
      this._currentState.onLeave(StateMachineManager.InvalidState);
    this._stateDic.clear();
    this._currentState = null;
  }
}
